//
//  UserAccount.swift
//  Weibo
//
//  Created by .. on 16/5/1.
//  Copyright © 2016年 Lizhuo. All rights reserved.
//

import UIKit
import SVProgressHUD

class UserAccount: NSObject, NSCoding {
     /// 用户授权的唯一票据，用于调用微博的开放接口，同时也是第三方应用验证微博用户登录的唯一票据，第三方应用应该用该票据和自己应用内的用户建立唯一影射关系，来识别登录状态，不能使用本返回值里的UID字段来做登录识别。
    var access_token: String?
     ///access_token的生命周期，单位是秒数
    var expires_in: NSNumber? {
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in!.doubleValue)
        }
    }
     /// 授权用户的UID，本字段只是为了方便开发者，减少一次user/show接口调用而返回的，第三方应用不能用此字段作为用户登录状态的识别，只有access_token才是用户授权的唯一票据
    var uid: String?
        /// 保存用户的过期时间
    var expires_date: NSDate?
        /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
        /// 用户昵称
    var screen_name: String?
    
    init(dict: [String: AnyObject]) {
        super.init()
//        access_token = dict["access_token"] as? String
//        expires_in = dict["expires_in"] as? NSNumber
//        uid = dict["uid"] as? String 

        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print(key)
    }
    
    override var description: String {
        //1.定义属性数组
        let properties = ["access_token", "expires_in", "uid", "expires_date", "avatar_large", "screen_name"]
        //2.根据属性数组，将属性转换为字典
        let dict = self.dictionaryWithValuesForKeys(properties)
        //3.将字典转换为字符串
        return "\(dict)"
    }
    
    /**
     返回用户是否登录
     */
    class func userLogin() -> Bool {
        return UserAccount.loadAccount() != nil
    }
    
    func loadUserInfo(finished: (account: UserAccount?, error: NSError?) -> ()) {
        assert(access_token != nil, "没有授权")
        
        let path = "2/users/show.json"
        let params = ["access_token": access_token!, "uid": uid!]
        
        NetworkTools.sharedNetworkTools().GET(path, parameters: params, success: { (_, JSON) in
            //1.判断字典是否有值
            if let dict = JSON as? [String: AnyObject] {
                self.screen_name = dict["screen_name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
                //保存用户信息
//                self.saveAccount()
                finished(account: self, error: nil)
                return
            }
             finished(account: nil, error: nil)
            }) { (_, error) in
               finished(account: nil, error: error)
        }
        
    }
    
    //MARK: - 保存和读取
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: "account.plist".cacheDir())
    }
    
    //加载授权模型
    static var account: UserAccount?
    class func loadAccount() -> UserAccount? {
        //1.判断是否已经加载过
        if account != nil {
            return account
        }
        //2.加载授权模型
        account = NSKeyedUnarchiver.unarchiveObjectWithFile("account.plist".cacheDir()) as? UserAccount
        //3.判断授权信息是否过期
        if account?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            //已经过期
            return nil
        }
        
        return account
    }
    
    //MARK: - NSCoding
    //将对象写入到文件中
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    //从文件中读取对象
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
}
